package com.egao.common.module.pushInformation.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.pushInformation.PushInformationConstants;
import com.egao.common.module.pushInformation.entity.PushInformation;
import com.egao.common.module.pushInformation.entity.PushInformationPosition;
import com.egao.common.module.pushInformation.param.PushInformationParam;
import com.egao.common.module.pushInformation.service.PushInformationPositionService;
import com.egao.common.module.pushInformation.service.PushInformationService;
import com.egao.common.module.system.entity.College;
import com.egao.common.module.system.entity.PushViewRecord;
import com.egao.common.module.system.service.CollegeService;
import com.egao.common.module.system.service.PushViewRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Api(tags = "精准匹配信息推送控制器")
@RestController
@RequestMapping("${api}")
public class PushInformationController extends BaseController {

    @Resource
    private PushInformationService pushInformationService;
    @Resource
    private PushInformationPositionService pushInformationPositionService;
    @Resource
    private CollegeService collegeService;
    @Resource
    private PushViewRecordService pushViewRecordService;

    @PreAuthorize("hasAnyAuthority('school:push-information:list', 'college:push-information:list')")
    @ApiOperation("列表")
    @GetMapping("/push-information/page")
    public PageResult<PushInformation> page(HttpServletRequest request) {
        // 查询已推送信息
        PageParam<PushInformationParam> pageParam = new PageParam<>(request);
        pageParam.getPageData().put("pushState", PushInformationConstants.PUSH_STATE_SUCCESS);

        // 没有校级权限 查询学院数据
        if (!hasAuthority("school:push-information:list")) {
            // 登录人学院代码
            String collegeCode = getLoginUser().getCollegeCode();
            if (StrUtil.isBlank(collegeCode)) {
                return new PageResult<>();
            }

            // 登录人学院
            College college = collegeService.getByCode(collegeCode);
            if (college == null) {
                return new PageResult<>();
            }

            pageParam.getPageData().put("collegeName", college.getName());
        }

        List<PushInformation> list = pushInformationService.listPage(pageParam);
        return new PageResult<>(list, pageParam.getTotal());
    }

    @PreAuthorize("hasAnyAuthority('school:push-information:list', 'college:push-information:list')")
    @ApiOperation("详情")
    @GetMapping("/push-information/detail/{id}")
    public JsonResult detail(@PathVariable("id") Integer id) {
        PushInformation pushInformation = pushInformationService.getById(id);
        if (pushInformation == null) {
            return JsonResult.error("内容不存在");
        }

        // 查询推送信息职位
        List<PushInformationPosition> pushInformationPositionList = pushInformationPositionService.list(new LambdaQueryWrapper<PushInformationPosition>()
                .eq(PushInformationPosition::getPushInformationId, pushInformation.getId())
        );
        pushInformation.setPositionList(pushInformationPositionList);

        // 没有校级权限 记录学院查看
        if (!hasAuthority("school:push-information:list")) {
            int count = pushViewRecordService.count(new LambdaQueryWrapper<PushViewRecord>()
                    .eq(PushViewRecord::getUserId, getLoginUserId())
                    .eq(PushViewRecord::getCollegeCode, getLoginUser().getCollegeCode())
                    .eq(PushViewRecord::getPushInformationId, pushInformation.getId())
            );
            if (count == 0) {
                PushViewRecord pushViewRecord = new PushViewRecord();
                pushViewRecord.setUserId(getLoginUserId());
                pushViewRecord.setCollegeCode(getLoginUser().getCollegeCode());
                pushViewRecord.setPushInformationId(pushInformation.getId());
                pushViewRecordService.save(pushViewRecord);
            }
        }

        return JsonResult.ok().setData(pushInformation);
    }

    @PreAuthorize("hasAnyAuthority('school:push-information:list', 'college:push-information:list')")
    @ApiOperation("列表")
    @GetMapping("/push-information/list")
    public PageResult<PushInformation> list(HttpServletRequest request) {
        // 查询已推送信息
        PageParam<PushInformationParam> pageParam = new PageParam<>(request);
        pageParam.getPageData().put("pushState", PushInformationConstants.PUSH_STATE_SUCCESS);
        // 查询全部条数
        pageParam.setSize(-1L);

        // 没有校级权限 查询学院数据
        if (!hasAuthority("school:push-information:list")) {
            // 登录人学院代码
            String collegeCode = getLoginUser().getCollegeCode();
            if (StrUtil.isBlank(collegeCode)) {
                return new PageResult<>();
            }

            // 登录人学院
            College college = collegeService.getByCode(collegeCode);
            if (college == null) {
                return new PageResult<>();
            }

            pageParam.getPageData().put("collegeName", college.getName());
        }

        List<PushInformation> list = pushInformationService.listPage(pageParam);
        List<PushInformationPosition> pushInformationPositionList = pushInformationPositionService.list();

        for (PushInformation pushInformation : list) {
            pushInformation.setPositionList(pushInformationPositionList.stream().
                    filter(d -> d.getPushInformationId().equals(pushInformation.getId())).collect(Collectors.toList())
            );

            String categoryLabel = "";
            if (1 == pushInformation.getCategory()) {
                categoryLabel = "招聘信息";
            }
            if (2 == pushInformation.getCategory()) {
                categoryLabel = "宣讲会";
            }
            if (3 == pushInformation.getCategory()) {
                categoryLabel = "空中宣讲会";
            }
            pushInformation.setCategoryLabel(categoryLabel);

            pushInformation.setReadStateLabel(pushInformation.getReadState() == 0 ? "已查看" : "未查看");
            pushInformation.setResumeStateLabel(pushInformation.getResumeState() == 0 ? "已发送" : "未发送");

            StringBuilder jobs = new StringBuilder();
            for (PushInformationPosition pushInformationPosition : pushInformationPositionList) {
                if (pushInformation.getId().equals(pushInformationPosition.getPushInformationId())) {
                    String job = StrUtil.format("{}({})",
                            pushInformationPosition.getPositionName(),
                            pushInformationPosition.getMatching()
                    );
                    jobs.append(job).append(",");
                }
            }
            pushInformation.setJobs(StrUtil.removeSuffix(jobs.toString(), ","));
        }

        return new PageResult<>(list, pageParam.getTotal());
    }
}
